<?php
namespace dgwht\ file;
use Qcloud\ Cos\ Client;

class Cos {

	public $Msg;
	private $Bucket;
	private $Region;
	private $SecretId;
	private $SecretKey;
	private $Host;
	private $Key;
	private $COS;

	function __construct( $config = [] ) {
		//AccessKey ID
        $this->SecretId = isset($config['appid']) ? $config['appid'] : '';
		//AccessKey Secret
        $this->SecretKey = isset($config['appkey']) ? $config['appkey'] : '';
		//储存桶
        $this->Bucket = isset($config['bucket']) ? $config['bucket'] : '';
		//地域
        $this->Region = isset($config['region']) ? $config['region'] : '';
		$this->COS = new Client([
			'region' => $this->Region,
			'credentials' => [
				'secretId' => $this->SecretId,
				'secretKey' => $this->SecretKey,
			],
		]);
	}

	public function up( $key, $srcPath, $headers=[] ) {
		$this->Key = $key;
		try {
			$data =  array(
				'Bucket' => $this->Bucket,
				'Key' => $key,
				'Body' => fopen( $srcPath, "rb" )
			);
			if(isset($headers)){
				$data = array_merge($data, $headers);
			}
			$ret = $this->COS->putObject($data);
			if ( !isset($ret[ 'Location' ] )) {
				$this->Msg = "上传失败";
				return false;
			}
		} catch ( \Exception $e ) {
			$this->Msg = $e;
			return false;
		}
		$this->Msg = "OK";
		return true;
	}
	
	public function getSignUrl($time, $key){
		$time = "+{$time} seconds";
		if($key==null) $key = $this->Key;
		if($key==null) return false;
		try {
			$signedUrl = $this->COS->getPresignetUrl( 'getObject', array(
				'Bucket' => $this->Bucket,
				'Key' => $key,
			), $time );
			return $signedUrl;
		} catch ( \Exception $e ) {
			return false;
		}
	}
	
	public function del($key){
		if(is_array($key)){
			$keys = [];
			foreach($key as $v){
				array_push($keys,["Key" => $v]);
			}
			$key = $keys;
		}else{
			$key = [["Key" => $key]];
		}
		try {
			$result = $this->COS->deleteObjects( array(
				'Bucket' => $this->Bucket,
				'Objects' => $key,
			) );
			return true;
		} catch ( \Exception $e ) {
			return false;
		}
	}

}